package com.course.redis.controller;

import cn.hutool.core.bean.BeanUtil;
import com.course.common.enums.ApiConstant;
import com.course.common.exception.ParameterException;
import com.course.common.model.vo.SignInUserInfo;
import com.course.common.response.BaseResponse;
import com.course.common.util.AssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION:
 * @Author: 涂玄武
 * @DATE: 2021/6/28 15:57
 */
public class BaseController {

    @Value("${service.name.oauth2-server}")
    private String oauthServerName;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 打印日志
     */
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取登录用户信息
     *
     * @param accessToken
     * @return
     */
    protected SignInUserInfo loadSignInDinerInfo(String accessToken) {
        // 必须登录
        AssertUtil.mustLogin(accessToken);
        String url = oauthServerName + "user/me?access_token={accessToken}";
        BaseResponse response = restTemplate.getForObject(url, BaseResponse.class, accessToken);
        if (response.getCode() != ApiConstant.SUCCESS_CODE) {
            throw new ParameterException(response.getCode(), response.getMsg());
        }
        SignInUserInfo dinerInfo = BeanUtil.fillBeanWithMap((LinkedHashMap) response.getData(),
                new SignInUserInfo(), false);
        if (dinerInfo == null) {
            throw new ParameterException(ApiConstant.NO_LOGIN_CODE, ApiConstant.NO_LOGIN_MESSAGE);
        }
        return dinerInfo;
    }
}
